var pattern = new RegExp(/\?Code=(\S*)/g);
var idx = pattern.exec(window.location.href);
var Data02 = [], Data03=[], i1=0, i2=0, StageCode, StageCode2, Datas03=[], rows=[];

var grid02 = $('#jgTable02'), 
    grid03 = $('#jgTable03'),
    ItemCode = $('input[data-field="ItemCode"]'),
    ItemName = $('input[data-field="ItemName"]'),
    ItemObject = $('input[data-field="ItemObject"]'),
    ItemMainTable = $('input[data-field="ItemMainTable"]'),
    ItemLink = $('input[data-field="ItemLink"]');

$(function(){
    requestOptions();
    requestAjax();
    gridInit02();
    gridInit03();
    $("li[data-opt='add']").on('click', addCode);
    $("li[data-opt='save']").on('click', saveCode);
    $("li[data-opt='back']").on('click', back);
    $('#Btn02').on('click', Add02);
    $('#Btn03').on('click', Add03);
    $('.modal-data').draggable();
    $('#m_StageCode').on('change', function(){
        $('#m_StageName').val($(this).find('option:selected').text());
    });
    $('#m_StageName').on('change', function(){
        $('#m_StageCode').val($(this).find('option:selected').text());
    });
});

function requestOptions(){    //MDM0058/MDM005802
    var postDataS = Object.create(postData);
    postDataS.Method = 'Q';
    postDataS.page = '1';
    postDataS.rows = '500';
    postDataS.sidx = 'Code';
    postDataS.sord = 'asc';
    postDataS.Content = {
        SearchText: ''
    }
    $.ajax({
        async: false,
        type: 'post',
        url: mdmPath + '/MDM0058/MDM005802',
        data: postDataS,
        dataType: 'json',
        success: function (re) {
            if (re.Status == 200) {
                loadS(re);
            } else if (re.Status == -999) {
                alert_QX($('body'), re.Message);
            } else {
                alert(re.Message);
            }
        }
    });
}
function loadS(re){
    if(re.Content){
        rows = re.Content.rows;
        var html_code = '', html_name = '';
        rows.forEach(function(v,i,a) {
            html_code += '<option value="'+v.Name+'">'+v.Code+'</option>';
            html_name += '<option value="'+v.Code+'">'+v.Name+'</option>';
        });
        $('#m_StageCode').html(html_code);
        $('#m_StageCode2').html(html_code);
        $('#m_StageName').html(html_name);
    }
};

function requestAjax(){ //MDM0056/MDM005603
    if (idx) {
        var _postData = Object.create(postData);    //请求头
        _postData.Method = 'Q';
        _postData.Content = {
            Code: idx[1]
        }
        $.ajax({
            async: false,
            type: 'post',
            url: mdmPath + '/MDM0056/MDM005603',
            data: _postData,
            dataType: 'json',
            success: function (re) {
                if (re.Status == 200) {
                    loadAjax(re);
                } else if (re.Status == -999) {
                    alert_QX($('body'), re.Message);
                } else {
                    alert(re.Message);
                }
            }
        });
    }
}
function loadAjax(re) {
    Data02 = re.Content.rows.MDM005602;
    Datas03 = re.Content.rows.MDM005603;
}

function gridInit02(){
    var gridData02 = Object.create(gridData);
    gridData02.rowNum = '-1';
    gridData02.grid = $('#jgTable02'); 
    gridData02.datatype = "local";
    gridData02.colModel = [
        {label:'代码', name:'Code', hidden:true, sortable:false},
        {label:'行号', name:'LineID', hidden:true, sortable:false},
        {label:'排序行号', name:'OrderById', hidden:true, sortable:false},
        {label:'阶段代码', name:'StageCode', sortable:false},
        {label:'阶段描述', name:'StageName', sortable:false},
        {label:'通过人数', name:'PassQty', sortable:false}
    ];
    gridData02.sortname = 'OrderById';
    gridData02.loadComplete = function(xhr){
        
    };
    gridData02.beforeRequest = function(){
        gridData02.grid.jqGrid("setGridParam", {
            data : Data02
        });
    };
    gridData02.onSelectRow = function(rowid,status){
        var rowData = grid02.jqGrid('getRowData', rowid); 
        StageCode = rowData.StageName;
        StageCode2 = rowData.StageCode;
        Data03 = [];
        Datas03.forEach(function(v,i,a){
            v.StageCode===StageCode2&&Data03.push(v);
        })
        grid03.jqGrid("clearGridData").trigger('reloadGrid');
    }
    gridInit(gridData02);
}

function gridInit03(){
    var gridData03 = Object.create(gridData);
    gridData03.rowNum = '-1';
    gridData03.grid = $('#jgTable03'); 
    gridData03.datatype = "local";
    gridData03.colModel = [
        {label:'代码', name:'Code', hidden:true, sortable:false},
        {label:'行号', name:'LineID', hidden:true, sortable:false},
        {label:'排序行号', name:'OrderById', hidden:true, sortable:false},
        {label:'阶段代码', name:'StageCode', sortable:false},
        {label:'工号', name:'EmployeeNo', sortable:false},
        {label:'员工名称', name:'Employee', sortable:false},
        {label:'链接定义', name:'Link', sortable:false}
    ];
    gridData03.sortname = 'Object';
    gridData03.loadComplete = function(xhr){
        gridSize()
    };
    gridData03.beforeRequest = function(){
        gridData03.grid.jqGrid("setGridParam", {
            data : Data03
        });
    };
    gridInit(gridData03);
}

//Style
function gridSize(){
    grid02.setGridWidth($('.u_contents').width() - 30);
    grid03.setGridWidth($('.u_contents').width() - 30);
}

//Options
function addCode(){
    window.open('MDM005602.html', '_blank'); 
}
function back(){
    window.open('MDM005601.html', '_self');
}
function Add02(){
    $('#Modal02').removeClass('hidden');
    $('#Submit02').unbind('click').bind('click', function(){
        //var strIds = grid02.jqGrid("getDataIDs");
        var arr = [];
        Data02.length!=0&&Data02.forEach(function(v,i,a){
            arr.push(v.StageCode);
        });
        // console.log(arr)
        // console.log($('#m_StageCode').find('option:selected').text())
        if(arr.indexOf($('#m_StageCode').find('option:selected').text())!=-1){
            myAlert('该阶段代码已存在');
        }else{
            i1++;
            grid02.addRowData(i1,{StageCode:$('#m_StageCode').find('option:selected').text(),StageName:$('#m_StageName').find('option:selected').text(),PassQty:$('#m_PassQty').val()},'last');
            Data02 = grid02.jqGrid('getRowData');
        }
        $('#Modal02').addClass('hidden');
    });
}
function Add03(){
    $('#Modal03').removeClass('hidden');
    $('#m_StageCode2').val(StageCode);
    $('#Submit03').unbind('click').bind('click', function(){
        if($('#m_StageCode2').val()){
            i2++;
            grid03.addRowData(i2,{EmployeeNo:$('#m_EmployeeNo').val(),Employee:$('#m_Employee').val(),StageCode:$('#m_StageCode2').find('option:selected').text(),Link:$('#m_Link').val()},'last');
            Datas03.push({EmployeeNo:$('#m_EmployeeNo').val(),Employee:$('#m_Employee').val(),StageCode:$('#m_StageCode2').find('option:selected').text(),Link:$('#m_Link').val()})
        }else {
            myAlert('阶段代码不能为空')
        }
        $('#Modal03').addClass('hidden');
    });
}
function saveCode(){
    var requestData = {
        Method: 'U',
        Content:{
            Code: ItemCode.val(),
            Name: ItemName.val(),
            Object: ItemObject.val(),
            MainTable: ItemMainTable.val(),
            Link: ItemLink.val(),
            MDM005602: Data02,
            MDM005603: Data03
        }
    }
    for(i in postData){
        requestData[i] = postData[i];
    }
    if(idx){
        requestData.Method = 'U'
    }else{
        requestData.Method = 'A'
    }
    console.log(requestData)
    $.ajax({
        type: "post",
        url: mdmPath + '/MDM0056/MDM005601',
        data: requestData,
        dataType: "json",
        success: function(re) {
            if(re.Status==200){
                myAlert('保存成功')
            }else{
                myAlert(re.Message)
            }
        }
    });
}